<template>
  <div>
    <h3>运动员教育经历统计</h3>
    <div class="table-body">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row style="margin-bottom: 20px;" :gutter="20">
            <el-col :span="6">
            </el-col>
            <el-col :span="9">
              <sportChangesportItem ref="sport2sportItem" search="search"
                :sportChangesportItemData="sportChangesportItemData" @selectDataChange='searchSelectDataChange' />
            </el-col>
            <el-col :span="4" :offset="1">
              <el-select v-model="searchForm.educationTypeId" size="small" filterable clearable placeholder="选择受教育程度">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_educationType" :key="index">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.eductionLevelId" size="small" filterable clearable placeholder="选择学位">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_eductionLevel" :key="index">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-button type="success" icon="el-icon-plus" size="medium" @click="insertEvent">新增</el-button>
              <el-button type="success" icon="el-icon-printer" size="medium" @click="exportData">导出</el-button>
              <el-button type="success" icon="el-icon-printer" size="medium" @click="printEvent">打印</el-button>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="right" unlink-panels style="width: 80%;"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="5">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;">
                搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="3">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="player" title="运动员" sortable></vxe-table-column>
        <vxe-table-column field="sport" title="运动项目" sortable></vxe-table-column>
        <vxe-table-column field="sportItem" title="运动小项" sortable></vxe-table-column>
        <vxe-table-column field="coach" title="教职员" sortable></vxe-table-column>
        <vxe-table-column field="openDate" title="开始时间" sortable></vxe-table-column>
        <vxe-table-column field="closeDate" title="结束时间" sortable></vxe-table-column>
        <vxe-table-column field="schoolName" title="学校名称" sortable></vxe-table-column>
        <vxe-table-column field="educationType" title="受教育程度" sortable></vxe-table-column>
        <vxe-table-column field="major" title="专业" sortable></vxe-table-column>
        <vxe-table-column field="eductionLevel" title="学位" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="110">
          <template #default="{ row,rowIndex }">
            <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
            <el-button @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle></el-button>
          </template>
        </vxe-table-column>
        <vxe-table-column field="createUser" title="录入人" sortable></vxe-table-column>
        <vxe-table-column field="checkUser" title="审核人" sortable>
          <template #default="{ row }">
            <span v-if="row.checkUserId!=0">{{row.checkUser}}</span>
            <el-link v-else @click="checkedEvent(row)" type="success">{{row.checkUser}}</el-link>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <vxe-modal v-model="insertModal" title="运动员教育经历统计">
      <template #default>
        <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="110px">
          <sportChangesportItem ref="sport2sportItem" :sportChangesportItemData="sportChangesportItemData" :playerValdata="true" :isEmp="true"
            :showPlayer="true" @selectDataChange='insertSelectDataChange' />
          <el-form-item label="开始时间" prop="openDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.openDate" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="closeDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.closeDate" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="学校名称" prop="schoolName">
            <el-input v-model="insertForm.schoolName"></el-input>
          </el-form-item>
          <el-form-item label="受教育程度" prop="educationTypeId">
            <el-select v-model="insertForm.educationTypeId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_educationType" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专业" prop="major">
            <el-input v-model="insertForm.major"></el-input>
          </el-form-item>
          <el-form-item label="学位" prop="eductionLevelId">
            <el-select v-model="insertForm.eductionLevelId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_eductionLevel" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
  import {
    player_education,
    player_education_insert,
    player_education_update,
    player_education_delete,
    player_education_check,
    pcm4player,
  } from '@/api/person.js'
  import {
    sport_by_org,
    userId2EmpName,
    sport_item,
    coach_by_org,
  } from '@/api/dict.js'
  import sportChangesportItem from '@/components/sport2sportItem/sport2sportItem.vue'
  export default {
    components: {
      sportChangesportItem
    },
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        dict_player: {},
        dict_pid2player: {},
        dict_pid2playerId: {},
        dict_pid2sport: {},
        dict_pid2sportItem: {},
        dict_pid2coach: {},
        dict_sport: {},
        dict_sportItem: {},
        dict_coach: {},
        dict_educationType: {
          1: "学龄前",
          2: "小学",
          3: "初中",
          4: "高中",
          5: "中专",
          6: "大专",
          7: "本科",
          8: "硕士",
          9: "博士",
          10: "博士后",
        },
        dict_eductionLevel: {
          1: "学士学位",
          2: "硕士学位",
          3: "博士学位",
          4: "无",
          5: "小学",
        },
        dict_createUser: {},
        dict_checkUser: {},

        insertForm: {
          playerId: '',
          empId: '',
          sportId: '',
          sportItemId: '',
          openDate: '',
          closeDate: '',
          schoolName: '',
          educationTypeId: '',
          major: '',
          eductionLevelId: '',
        },
        searchForm: {
          empId: '',
          sportId: '',
          sportItemId: '',
          educationTypeId: '',
          eductionLevelId: '',
        },
        sportItemData: [],
        rules: {
          openDate: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
          schoolName: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
        },
        isInsert: true,
        flowId: '',
        pid: '',
        empData: {},
        sportChangesportItemData: {},
        search: false,
        currentIndex: null,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.player_education()
      })
    },
    computed: {
      openDateValid() {
        if (this.insertForm.openDate && this.insertForm.closeDate) {
          if (this.insertForm.openDate > this.insertForm.closeDate) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      }
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      searchSelectDataChange({
        sportId,
        sportItemId,
        person
      }) {
        this.searchForm.sportId = sportId
        this.searchForm.sportItemId = sportItemId
        this.searchForm.empId = person
      },
      insertSelectDataChange({
        sportId,
        sportItemId,
        person,
        playerId
      }) {
        this.insertForm.sportId = sportId
        this.insertForm.sportItemId = sportItemId
        this.insertForm.empId = person
        this.insertForm.playerId = playerId
      },
      clearTableFilter() {
        this.searchForm = {
          empId: '',
          sportId: '',
          sportItemId: '',
          educationTypeId: '',
          eductionLevelId: '',
        }
        this.doubleDate = ''
        this.sportChangesportItemData = {}
        this.player_education()
      },
      searchSubmit() {
        let data = {}
        if (this.searchForm.empId) data.empId = this.searchForm.empId
        if (this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if (this.searchForm.sportItemId) data.sportItemId = this.searchForm.sportItemId
        if (this.searchForm.educationTypeId) data.educationTypeId = this.searchForm.educationTypeId
        if (this.searchForm.eductionLevelId) data.eductionLevelId = this.searchForm.eductionLevelId
        if (this.doubleDate){
          data.startDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        player_education(data).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.page = {
              currentPage: 1,
              pageSize: 10,
              totalResult: 0
            }
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          player_education_delete({
            flowId: row.flowId,
            empId: row.empId
          }).then(res => {
            if (res.code === 200) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.flowId == row.flowId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      checkedEvent(row) {
        this.$confirm('注意：审核过之后，该条数据将不能再被修改', '审核', {
          confirmButtonText: '√通过审核',
          cancelButtonText: '放弃审核',
          type: 'warning'
        }).then(() => {
          player_education_check({
            flowId: row.flowId
          }).then(res => {
            if (res.code === 200) {
              this.player_education()
              this.$message.success('已审核.！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消审核.'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        if (row.checkUserId!=0) {
          this.$message.warning('已经审核过的数据不能修改')
        } else {
          this.flowId = row.flowId
          this.insertForm.empId = row.empId
          this.insertForm.playerId = this.dict_pid2playerId[row.pid]
          this.insertForm.sportId = this.dict_pid2sport[row.pid]
          this.insertForm.sportItemId = this.dict_pid2sportItem[row.pid]
          this.insertForm.openDate = row.openDate
          this.insertForm.closeDate = row.closeDate
          this.insertForm.schoolName = row.schoolName
          this.insertForm.educationTypeId = row.educationTypeId == 0 ? '' : row.educationTypeId + ''
          this.insertForm.major = row.major
          this.insertForm.eductionLevelId = row.eductionLevelId == 0 ? '' : row.eductionLevelId + ''
          this.sportChangesportItemData = {
            sportId: this.insertForm.sportId + '',
            sportItemId: this.insertForm.sportItemId==0?'':this.insertForm.sportItemId,
            person: this.insertForm.empId,
            playerId: this.insertForm.playerId,
          }
          this.isInsert = false
          this.insertModal = true
        }
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if (this.insertForm.playerId) data.playerId = this.insertForm.playerId
            if (this.insertForm.empId) data.empId = this.insertForm.empId
            if (this.insertForm.openDate) data.openDate = this.$moment(this.insertForm.openDate).format(
              'YYYY-MM-DD') + ' 00:00:00'
            if (this.insertForm.closeDate) data.closeDate = this.$moment(this.insertForm.closeDate).format(
              'YYYY-MM-DD') + ' 00:00:00'
            if (this.insertForm.schoolName) data.schoolName = this.insertForm.schoolName
            if (this.insertForm.educationTypeId) data.educationTypeId = this.insertForm.educationTypeId
            if (this.insertForm.major) data.major = this.insertForm.major
            if (this.insertForm.eductionLevelId) data.eductionLevelId = this.insertForm.eductionLevelId
            data.isPlayer = 1
            if (this.isInsert) {
              player_education_insert(data).then(res => {
                if (res.code === 200) {
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                  this.insertModal = false
                } else {
                  this.$message.error('保存失败了！')
                }
              })
            } else {
              data.flowId = this.flowId
              player_education_update(data).then(res => {
                if (res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.flowId==item.flowId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                } else {
                  this.$message.error('保存失败了！')
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.insertForm = {
          playerId: '',
          empId: '',
          sportId: '',
          sportItemId: '',
          openDate: '',
          closeDate: '',
          schoolName: '',
          educationTypeId: '',
          major: '',
          eductionLevelId: '',
        }
        this.sportChangesportItemData = {}
        this.isInsert = true
        this.insertModal = true
      },
      exportData() {
        this.$refs.XTable.exportData({
          filename: this.$store.state.user.org+'运动员'+this.$route.meta.title, type: 'csv',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEvent() {
        let topHtml = '<h2>运动员教育经历统计</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '运动员教育经历统计',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      player_education() {
        this.loading = true
        player_education().then(res => {
          if (res.code === 200 && res.data.length != 0) {
            this.init_data(res.data)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item => {
          item.player = this.dict_pid2player[item.pid]
          item.sport = this.dict_sport[this.dict_pid2sport[item.pid]]
          item.sportItem = this.dict_sportItem[this.dict_pid2sportItem[item.pid]]
          item.coach = this.dict_coach[this.dict_pid2coach[item.pid]]
          item.openDate = this.$moment(item.openDate).format('YYYY-MM-DD') == 'Invalid date' ? '' : this.$moment(
            item.openDate).format('YYYY-MM-DD')
          item.closeDate = this.$moment(item.closeDate).format('YYYY-MM-DD') == 'Invalid date' ? '' : this.$moment(
            item.closeDate).format('YYYY-MM-DD')
          item.educationType = this.dict_educationType[item.educationTypeId]
          item.eductionLevel = this.dict_eductionLevel[item.eductionLevelId]
          item.createUser = this.dict_userId2empName[item.createUserId]
          if (item.checkUserId&&item.checkUserId!='0') {
            item.checkUser = this.dict_userId2empName[item.checkUserId]
          } else {
            item.checkUser = '未审核'
          }
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          sport_by_org().then(res => {
            this.dict_sport = res
          })
          sport_item().then(res => {
            this.dict_sportItem = res
          })
          coach_by_org().then(res => {
            this.dict_coach = res
          })
          userId2EmpName().then(res => {
            this.dict_userId2empName = res
          })
          pcm4player().then(result => {
            var dict_player = {};
            var dict_pid2player = {}
            var dict_pid2playerId = {}
            var dict_pid2sport = {}
            var dict_pid2sportItem = {}
            var dict_pid2coach = {}
            for (var i = 0; i < result.data.length; i++) {
              dict_player[result.data[i].playerId] = result.data[i].name;
              dict_pid2player[result.data[i].pid] = result.data[i].name;
              dict_pid2playerId[result.data[i].pid] = result.data[i].playerId;
              dict_pid2sport[result.data[i].pid] = result.data[i].sportId;
              dict_pid2sportItem[result.data[i].pid] = result.data[i].sportItemId;
              dict_pid2coach[result.data[i].pid] = result.data[i].coachId;
            }
            this.dict_player = dict_player
            this.dict_pid2player = dict_pid2player
            this.dict_pid2playerId = dict_pid2playerId
            this.dict_pid2sport = dict_pid2sport
            this.dict_pid2sportItem = dict_pid2sportItem
            this.dict_pid2coach = dict_pid2coach
            resolve()
          })
        })
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
